Stored Procedures [dbo].[asi_GetUserKeyReferences]
Properties
PropertyValue
ANSI Nulls OnYes
Quoted Identifier OnYes
Parameters
NameData TypeMax Length (Bytes)
@userKeyuniqueidentifier16
SQL Script
CREATE PROCEDURE [dbo].[asi_GetUserKeyReferences]
    @userKey uniqueidentifier
AS
BEGIN
    DECLARE @tableName nvarchar(255)
    DECLARE @columnName nvarchar(255)
    DECLARE @sql nvarchar(4000)
    DECLARE @results table (UserKey uniqueidentifier, TableName nvarchar(255), ColumnName nvarchar(255))
    DECLARE @exists bit
    DECLARE theCursor CURSOR FAST_FORWARD FOR
        SELECT isc.TABLE_NAME, isc.COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS isc INNER JOIN INFORMATION_SCHEMA.TABLES ist ON isc.TABLE_NAME = ist.TABLE_NAME
        WHERE isc.COLUMN_NAME like '%UserKey' AND isc.DATA_TYPE = 'uniqueidentifier' AND ist.TABLE_TYPE = 'BASE TABLE' AND ist.TABLE_SCHEMA = 'dbo'
    OPEN theCursor
    FETCH NEXT from theCursor INTO @tableName, @columnName
    WHILE (@@FETCH_STATUS =0)
    BEGIN
        SET @sql = N'IF EXISTS (SELECT 1 FROM ' + @tableName + N' WHERE ' + @columnName + N' = @uKey) BEGIN SET @e = 1 END ELSE BEGIN SET @e = 0 END';
        EXEC sp_executesql @sql, N'@e bit out, @uKey uniqueidentifier', @exists out, @userKey
        IF (@exists = 1) INSERT INTO @results VALUES (@userKey, @tableName, @columnName)
        FETCH NEXT from theCursor INTO @tableName, @columnName
    END
    CLOSE theCursor
    DEALLOCATE theCursor
    SELECT * from @results
END

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[asi_GetAccessKeyReferences]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[asi_GetAccessKeyReferences]

GO
Uses